import { createI18n, useI18n } from 'vue-i18n'
import { computed } from 'vue'
import { getLang, setLang } from '@/utils/storage'
import lang from './lang/index'
import type { Ref } from 'vue'

export const i18n = createI18n({
  locale: getLang() || 'zh',
  fallbackLocale: 'zh',
  legacy: false,
  globalInjection: true,
  // @ts-ignore
  messages: lang
})

export const i18nGlobal = i18n.global

/** 切换语言
 */
type UseChangeI18n = { currentLang: Ref<string>; changeLang: (lang: 'zh' | 'en') => void }
export const useChangeI18nHook = (): UseChangeI18n => {
  const { locale } = useI18n()

  const currentLang = computed(() => {
    const { locale } = useI18n()
    return locale.value
  })

  const changeLang = (lang: 'zh' | 'en'): void => {
    locale.value = lang
    setLang(lang)
  }

  return {
    currentLang,
    changeLang
  }
}
